package com.example.blog.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.blog.dao.domain.Archives;
import com.example.blog.dao.mapper.ArticleBodyMapper;
import com.example.blog.dao.mapper.ArticleMapper;
import com.example.blog.dao.mapper.ArticleTagMapper;
import com.example.blog.dao.pojo.*;
import com.example.blog.service.*;
import com.example.blog.utils.UserThreadLocal;
import com.example.blog.vo.*;
import com.example.blog.vo.param.ArticleParam;
import com.example.blog.vo.param.PageParams;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private TagsService tagsService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private ArticleBodyMapper articleBodyMapper;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private ThreadService threadService;

    @Autowired
    private ArticleTagMapper articleTagMapper;

    @Override
    public List<Article> findNewArticles(int limit) {
        // 查询条件
        QueryWrapper<Article> queryWrapper = new QueryWrapper();
        // 通过view_counts字段倒叙查询
        queryWrapper.orderByDesc("create_date");
        // 查询文章的 id, title
        queryWrapper.select("id", "title");
        //无视优化规则直接拼接到 sql 的最后(有sql注入的风险,请谨慎使用) 将last括号的内容拼接到sql语句的最后
        queryWrapper.last("limit " + limit);
        List<Article> newArticles = articleMapper.selectList(queryWrapper);
        // javabean和传入前端数据类型相同，不需要转换（copylist）
        return newArticles;
    }

    @Override
    public List<Archives> listArchives() {

        return articleMapper.listArchives();
    }

    @Override
    public ArticleVo findArticleById(Long articleId) {
        /**
         * 1.根据文章id 查询文章信息
         * 2.根据bodyid 和 categoryid 去做关联查询
         */
        Article article = articleMapper.selectById(articleId);

        // 增加阅读数
        // 查看完文章了，增加阅读数 有没有问题？
        // 查看完文章了，本应该直接返回数据，这时候做个一个更新操作，更新时加写锁，阻碍其他读操作，性能就会降低 （没法解决）
        // 更新操作，增加了本次接口的耗时，如果更新一旦出现问题，不能影响 文章详情的操作
        // 线程池 可以把更新操作 扔到线程池中去执行， 这样就和主线程不相关了
        threadService.updateViewCount(articleMapper, article);

        return copy(article, true, true, true, true);
    }

    @Override
    public Result insert(ArticleParam articleParam) {
        // 获取当前登录的用户
        SysUser sysUser = UserThreadLocal.get();
        // 文章
        Article article = new Article();
        article.setTitle(articleParam.getTitle());
        article.setSummary(articleParam.getSummary());
        article.setCommentCounts(0);
        article.setViewCounts(0);
        article.setAuthorId(sysUser.getId());
        article.setBodyId(-1l);
        article.setCategoryId(Long.parseLong(articleParam.getCategory().getId()));
        article.setWeight(Article.Article_Common);
        article.setCreateDate(System.currentTimeMillis());
        articleMapper.insert(article);

        // tag   文章 和标签的中间表
        List<TagVo> tagVos = articleParam.getTags();
        if (tagVos != null) {
            for (TagVo tagVo : tagVos) {
                ArticleTag articleTag = new ArticleTag();
                articleTag.setArticleId(article.getId());
                articleTag.setTagId(Long.parseLong(tagVo.getId()));
                articleTagMapper.insert(articleTag);
            }
        }

        // ArticleBody
        ArticleBody articleBody = new ArticleBody();
        articleBody.setContent(articleParam.getBody().getContent());
        articleBody.setContentHtml(articleParam.getBody().getContentHtml());
        articleBody.setArticleId(article.getId());
        articleBodyMapper.insert(articleBody);

        // 更新文章 bodyid 并且返回 文章id
        article.setBodyId(articleBody.getId());
        articleMapper.updateById(article);
        ArticleVo articleVo = new ArticleVo();
        articleVo.setId(String.valueOf(article.getId()));

        return Result.success(articleVo);
    }

    @Override
    public List<Article> findHotArticles(int limit) {

        // 查询条件
        QueryWrapper<Article> queryWrapper = new QueryWrapper();
        // 通过view_counts字段倒叙查询
        queryWrapper.orderByDesc("view_counts");
        // 查询文章的 id, title
        queryWrapper.select("id", "title");
        //无视优化规则直接拼接到 sql 的最后(有sql注入的风险,请谨慎使用) 将last括号的内容拼接到sql语句的最后
        queryWrapper.last("limit " + limit);
        List<Article> hotArticles = articleMapper.selectList(queryWrapper);
        // javabean和传入前端数据类型相同，不需要转换（copylist）
        return hotArticles;
    }

    /**
     * 分页查询文章 数据库表
     *
     * @param pageParams
     * @return
     */

    @Override
    public List<ArticleVo> listArticlesPage(PageParams pageParams) {
        //分页查询条件
        Page<Article> page = new Page<>(pageParams.getPage(), pageParams.getPageSize());
        IPage<Article> articleIPage = articleMapper.listArticles(
                page,
                pageParams.getCategoryId(),
                pageParams.getTagId(),
                pageParams.getYear(),
                pageParams.getMonth());
        List<Article> records = articleIPage.getRecords();
        return copyList(records, true,true);
    }
//    @Override
//    public List<ArticleVo> listArticlesPage(PageParams pageParams) {
//
//        //分页查询条件
//        Page<Article> page = new Page<>(pageParams.getPage(), pageParams.getPageSize());
//        //实体对象封装操作类
//        LambdaQueryWrapper<Article> queryWrapper = new LambdaQueryWrapper<>();
//        //是否置顶进行排序
//        //order by create_date desc
//        queryWrapper.orderByDesc(Article::getWeight, Article::getCreateDate);
//
//        // 判断不为空，加上判断条件
//        if (pageParams.getCategoryId() != null) {
//            //相当于在sql 语句后加上 and category_id = #{categoryId}
//            queryWrapper.eq(Article::getCategoryId, pageParams.getCategoryId());
//        }
//
//        List<Long> articleIds = new ArrayList<>();
//        if (pageParams.getTagId() != null) {
//            LambdaQueryWrapper<ArticleTag> articleTagLambdaQueryWrapper = new LambdaQueryWrapper<>();
//            articleTagLambdaQueryWrapper.select(ArticleTag::getArticleId);
//            articleTagLambdaQueryWrapper.eq(ArticleTag::getTagId, pageParams.getTagId());
//            List<ArticleTag> articleTags = articleTagMapper.selectList(articleTagLambdaQueryWrapper);
//            for (ArticleTag articleTag : articleTags) {
//                articleIds.add(articleTag.getArticleId());
//            }
//            if (articleIds.size() > 0) {
//                queryWrapper.in(Article::getId, articleIds);
//            }
//
//        }
//
//        Page<Article> articlePage = articleMapper.selectPage(page, queryWrapper);
//
//        //能直接返回吗？ 很明显不能
//        List<Article> records = articlePage.getRecords();
//        List<ArticleVo> articleVoList = copyList(records, true, true);
//
//        return articleVoList;
//    }

    private List<ArticleVo> copyList(List<Article> records, boolean isAuthor, boolean isTags) {
        List<ArticleVo> articleVoList = new ArrayList<>();
        for (Article record : records) {
            articleVoList.add(copy(record, isAuthor, isTags, false, false));
        }
        return articleVoList;
    }


    // Article.class 转 ArticleVo.class
    private ArticleVo copy(Article article, boolean isAuthor, boolean isTags, boolean isArticleBody, boolean isCategory) {
        ArticleVo articleVo = new ArticleVo();
        articleVo.setId(String.valueOf(article.getId()));
        BeanUtils.copyProperties(article, articleVo);
        //创作时间类型不同
        articleVo.setCreateDate(new DateTime(article.getCreateDate()).toString("yyyy-MM-dd HH:mm"));
        //并不是所有文章都需要“作者” 和 “标签”
        if (isTags) {
            articleVo.setTags(tagsService.findTagsByArticleId(article.getId()));
        }
        if (isAuthor) {
            articleVo.setAuthor(sysUserService.findSysUserById(article.getAuthorId()).getNickname());
        }

        if (isArticleBody) {
            ArticleBodyVo articleBody = findArticleBodyByid(article.getBodyId());
            articleVo.setBody(articleBody);
        }
        if (isCategory) {
            CategoryVo categoryVo = categoryService.findCategoryById(article.getCategoryId());
            articleVo.setCategory(categoryVo);
        }
        return articleVo;
    }

    private ArticleBodyVo findArticleBodyByid(Long id) {
        ArticleBody articleBody = articleBodyMapper.selectById(id);
        ArticleBodyVo articleBodyVo = new ArticleBodyVo();
        articleBodyVo.setContent(articleBody.getContent());
        return articleBodyVo;
    }
}
